package com.niannian.wxapi;

import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.niannian.BaseActivity;
import com.niannian.R;
import com.niannian.activity.CreateFamilyActivity;
import com.niannian.activity.ForgetPasswdOneActivity;
import com.niannian.activity.HomeActivity;
import com.niannian.activity.RegisterOneActivity;
import com.niannian.activity.RegisterThereActivity;
import com.niannian.dialog.YesNoDialog2;
import com.niannian.dialog.YesNoDialog2.onSimpleOnCancelListener;
import com.niannian.dialog.YesNoDialog2.onSimpleOnClicklListener;
import com.niannian.util.AsyncHandle;
import com.niannian.util.Common;
import com.niannian.util.ErrorCode;
import com.niannian.util.MyTextWatcher;
import com.niannian.util.UmengPage;
import com.niannian.web.nnSyncApi;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;
import com.umeng.fb.FeedbackAgent;

public class WXEntryActivity extends BaseActivity implements IWXAPIEventHandler {
	private EditText reg_phone_login, reg_password_login;
	private Button btn_login;
	RelativeLayout rl_weix_login;
	private TextView tv_forgotpassword, tv_our;
	String acct = "";
	String passwd = "";
	FeedbackAgent fb;
	TextView tv_register_phone;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.activity_login);
		fb = new FeedbackAgent(this);
		// check if the app developer has replied to the feedback or not.
		fb.sync();
		if (0 == getIntent().getIntExtra("from", 0)) {
			isgetweix = true;
		} else {
			isgetweix = false;
		}

		addActToGroup("logins", this);
		initView();
		setLister();
		initTopView();
	}

	private IWXAPI api;
	public static String APP_id = "wx01720f58ea6c102c";
	public static String AppSecret = "72a0d6634d6d7caab68c11656fa51703";

	private void initView() {

		api = WXAPIFactory.createWXAPI(WXEntryActivity.this, APP_id, true);
		api.registerApp(APP_id);

		reg_phone_login = (EditText) findViewById(R.id.reg_phone_login);
		reg_password_login = (EditText) findViewById(R.id.reg_password_login);
		btn_login = (Button) findViewById(R.id.btn_login);
		rl_weix_login = (RelativeLayout) findViewById(R.id.rl_weix_login);
		tv_forgotpassword = (TextView) findViewById(R.id.tv_forgotpassword);
		tv_forgotpassword.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);// 下划线
		tv_our = (TextView) findViewById(R.id.tv_our);
		tv_our.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);// 下划线

		tv_register_phone = (TextView) findViewById(R.id.tv_register_phone);
		tv_register_phone.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);// 下划线
		reg_phone_login.addTextChangedListener(textWatcher);
		reg_password_login.addTextChangedListener(textWatcher);

		RadioButton rd_server_1;
		RadioButton rd_server_2;
		RadioButton rd_server_3;
		rd_server_1 = (RadioButton) findViewById(R.id.rd_server_1);
		rd_server_2 = (RadioButton) findViewById(R.id.rd_server_2);
		rd_server_3 = (RadioButton) findViewById(R.id.rd_server_3);

		rd_server_1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Common.ServerUrl = "http://api.niannian.me/";
			}
		});
		rd_server_2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Common.ServerUrl = "http://192.168.0.110:88/";

			}
		});
		rd_server_3.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Common.ServerUrl = "http://192.168.0.102:8000/";

			}
		});

	}

	private void setLister() {
		btn_login.setOnClickListener(new UserLoginOnClickListener());
		rl_weix_login.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				isgetweix = true;
				api = WXAPIFactory.createWXAPI(WXEntryActivity.this, APP_id, false);
				api.handleIntent(getIntent(), WXEntryActivity.this);

				SendAuth.Req req = new SendAuth.Req();
				req.scope = "snsapi_userinfo";
				req.state = "weix";
				api.sendReq(req);

				MobclickAgent.onEvent(WXEntryActivity.this, UmengPage.click_wechat_login);

			}
		});
		tv_forgotpassword.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				openActivity(ForgetPasswdOneActivity.class);
				startAnimationLeftToRight();
			}
		});

		tv_our.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				fb.startFeedbackActivity();
				startAnimationLeftToRight();
			}
		});

		tv_register_phone.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				openActivity(RegisterOneActivity.class);
				startAnimationLeftToRight();
			}
		});
	}

	// 头部视图
	private ImageView iv_top_left, iv_top_right;
	private TextView top_title;
	private LinearLayout iv_top_left2, top_title2;

	private void initTopView() {
		iv_top_left = (ImageView) findViewById(R.id.iv_top_left);
		iv_top_left2 = (LinearLayout) findViewById(R.id.iv_top_left2);
		iv_top_left.setVisibility(View.VISIBLE);
		iv_top_left2.setVisibility(View.GONE);

		top_title = (TextView) findViewById(R.id.top_title);
		top_title2 = (LinearLayout) findViewById(R.id.top_title2);
		top_title.setVisibility(View.VISIBLE);
		top_title2.setVisibility(View.GONE);
		top_title.setText("登录");

		iv_top_right = (ImageView) findViewById(R.id.iv_top_right);
		iv_top_right.setVisibility(View.GONE);
		iv_top_left.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				myfinish();
				destroyGroup("logins");
			}
		});

	}

	private MyTextWatcher textWatcher = new MyTextWatcher() {

		@Override
		public void onFocusChange(View view, boolean hasFocus) {
		};

		@Override
		public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
			String acct = reg_phone_login.getText().toString().trim();
			String upwd = reg_password_login.getText().toString().trim();
			if (!Common.empty(acct) && !Common.empty(upwd)) {
			//	btn_login.setEnabled(true);
			} else {
				//btn_login.setEnabled(false);
			}
		}
	};

	class UserLoginOnClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {

			acct = reg_phone_login.getText().toString().trim();
			passwd = reg_password_login.getText().toString().trim();
			if (acct.length() != 11) {
				Common.tip(WXEntryActivity.this, "请输入您的11位手机帐号");
				return;
			}

			switch (Common.checkPassword(passwd)) {
			case 1:
				Common.tip(WXEntryActivity.this, "密码应该是数字与字符的组合");
				return;
			case 2:
				Common.tip(WXEntryActivity.this, "密码太短，请至少输入6个字符");
				return;
			case 3:
				Common.tip(WXEntryActivity.this, "密码太长,请至多输入16个字符");
				return;
			}
			new Login().init(WXEntryActivity.this, null, true, "登录中...").execute();
		}
	}

	protected class Login extends AsyncHandle {

		protected void errorFinally(Map<String, Object> paramMap) {
			Common.tip(WXEntryActivity.this, "登录失败");
		}

		protected void handleData(JSONObject paramJSONObject, Map<String, Object> paramMap) throws JSONException {
			int retCode = paramJSONObject.getInt("code");
			if (retCode == ErrorCode.OK) {
				MobclickAgent.onEvent(WXEntryActivity.this, UmengPage.LOGIN_PRESS_OK);
			}
			LoginReturn(paramJSONObject);
		}

		protected String runTask(Map<String, Object> paramMap) {
			return nnSyncApi.login(acct, passwd);
		}
	}

	private void LoginReturn(JSONObject paramJSONObject) throws JSONException {

		int retCode = paramJSONObject.getInt("code");
		if (retCode == ErrorCode.OK) {
			try {

				JSONObject userJson = paramJSONObject.getJSONObject("data");

				userInfoManager.Json2DBUser(userJson);
				update_gUser();

				if (userInfoManager.info_completed == 0) {
					openActivity(RegisterThereActivity.class);
				} else {
					if (userInfoManager.family != 0) {
						openActivity(HomeActivity.class);
						// Common.tip(WXEntryActivity.this, "登录成功");

					} else {
						openActivity(CreateFamilyActivity.class);
						// initDialog();
					}
					myfinish();
					destroyGroup("logins");
				}
				// Common.tip(LoginActivity.this, "登录成功");
				return;

			} catch (Exception e) {
				// TODO: handle exception
			}
		} else if (20003 == retCode) {
			String msgString = "您的账号未设置密码, 或者您是被亲友邀请注册的用户. 为保障账号安全, 需要您重新设置登录密码.";
			Login20003(msgString);
		} else {
			Common.tip(WXEntryActivity.this, paramJSONObject.getString("msg"));
		}

	}

	YesNoDialog2 tip;

	private void initDialog() {
		tip = new YesNoDialog2(WXEntryActivity.this, "你没有加入任何家庭是否创建新家庭?");
		tip.setcancelButtonText("取消并退出");
		tip.setConfimButtonText("创建新家庭");
		tip.setOnCancelListener(new onSimpleOnCancelListener() {

			@Override
			public void onCancel() {
				tip.dismiss();
			}
		});
		tip.setOnConfimClickListener(new onSimpleOnClicklListener() {

			@Override
			public void onClick() {
				new createFamily().init(WXEntryActivity.this, null, true, "创建家庭中...").execute();
				tip.dismiss();
			}
		});
		tip.show();
	}

	protected class createFamily extends AsyncHandle {

		protected void errorFinally(Map<String, Object> paramMap) {
			Common.tip(WXEntryActivity.this, "创建家庭失败");
		}

		protected void handleData(JSONObject paramJSONObject, Map<String, Object> paramMap) throws JSONException {
			int retCode = paramJSONObject.getInt("code");
			if (retCode == ErrorCode.OK) {
				try {
					JSONObject fJson = paramJSONObject.getJSONObject("data");
					userInfoManager.family = fJson.getInt("id");
					userInfoManager.family_perm = 1;
					update_gUser();
					openActivity(HomeActivity.class);
					myfinish();
					destroyGroup("logins");
					Common.tip(WXEntryActivity.this, "创建家庭成功");
					return;
				} catch (Exception e) {
					// TODO: handle exception
				}
			} else {
				Common.tip(WXEntryActivity.this, paramJSONObject.getString("msg"));
			}
		}

		protected String runTask(Map<String, Object> paramMap) {
			return nnSyncApi.createFamily();
		}
	}

	YesNoDialog2 Login20003tip;

	private void Login20003(String msg) {
		Login20003tip = new YesNoDialog2(WXEntryActivity.this, msg);
		Login20003tip.setcancelButtonText("取消");
		Login20003tip.setHideCancel();
		Login20003tip.setConfimButtonText("确定");
		Login20003tip.setOnCancelListener(new onSimpleOnCancelListener() {

			@Override
			public void onCancel() {
				Login20003tip.dismiss();
			}
		});
		Login20003tip.setOnConfimClickListener(new onSimpleOnClicklListener() {

			@Override
			public void onClick() {
				openActivity(ForgetPasswdOneActivity.class);
				startAnimationLeftToRight();
				Login20003tip.dismiss();
			}
		});
		Login20003tip.show();
	}

	@Override
	public void onBackPressed() {
		myfinish();
		destroyGroup("logins");
	}

	@Override
	public void onReq(BaseReq arg0) {
		// TODO Auto-generated method stub

	}

	String code = "";

	@Override
	public void onResp(BaseResp arg0) {

		switch (arg0.errCode) {
		case BaseResp.ErrCode.ERR_OK:
			SendAuth.Resp resp = (SendAuth.Resp) arg0;
			code = resp.code;
			new WeixGetAccess_token().init(WXEntryActivity.this, null, true, "请稍等...").execute();
			break;

		default:
			break;
		}
	}

	Boolean isgetweix = true;

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (isgetweix) {
			api.handleIntent(getIntent(), WXEntryActivity.this);
			isgetweix = false;
		}

	}

	String access_token = "";
	String expires_in = "";
	String refresh_token = "";
	String openid = "";

	protected class WeixGetAccess_token extends AsyncHandle {

		protected void errorFinally(Map<String, Object> paramMap) {

		}

		protected void handleData(JSONObject paramJSONObject, Map<String, Object> paramMap) throws JSONException {

			// "access_token":"ACCESS_TOKEN",
			// "expires_in":7200,
			// "refresh_token":"REFRESH_TOKEN",
			// "openid":"OPENID",
			// "scope":"SCOPE"

			access_token = paramJSONObject.getString("access_token");
			expires_in = paramJSONObject.getString("expires_in");
			refresh_token = paramJSONObject.getString("refresh_token");
			openid = paramJSONObject.getString("openid");

			new WeixGetUserinfo().init(WXEntryActivity.this, null, true, "请稍等...").execute();
		}

		protected String runTask(Map<String, Object> paramMap) {
			return nnSyncApi.WeixGetAccess_token(code);
		}
	}

	String open_name = "", avatar_url = "";

	protected class WeixGetUserinfo extends AsyncHandle {

		protected void errorFinally(Map<String, Object> paramMap) {

		}

		protected void handleData(JSONObject paramJSONObject, Map<String, Object> paramMap) throws JSONException {
			open_name = paramJSONObject.getString("nickname");
			avatar_url = paramJSONObject.getString("headimgurl");

			new WeixupdataUserinfo().init(WXEntryActivity.this, null, true, "请稍等...").execute();
		}

		protected String runTask(Map<String, Object> paramMap) {
			return nnSyncApi.WeixGetUserinfo(access_token, openid);
		}
	}

	protected class WeixupdataUserinfo extends AsyncHandle {

		protected void errorFinally(Map<String, Object> paramMap) {

		}

		protected void handleData(JSONObject paramJSONObject, Map<String, Object> paramMap) throws JSONException {

			if (paramJSONObject.getInt("code") == ErrorCode.OK) {
				SharedPreferences sp = getSharedPreferences("userinfo", Context.MODE_PRIVATE);
				Editor edit = sp.edit();
				edit.putBoolean("weixfirst", true);
				edit.commit();
				MobclickAgent.onEvent(WXEntryActivity.this, UmengPage.wechat_login_success);
			}
			LoginReturn(paramJSONObject);
		}

		protected String runTask(Map<String, Object> paramMap) {
			return nnSyncApi.WeixupdataUserinfo(openid, access_token, open_name, avatar_url, refresh_token, expires_in);
		}
	}

}
